﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;

namespace VerificationCode
{
   public class DBHelper
    {
        /// <summary>
        /// 连接字符串
        /// </summary>
        private string ConnString { get; set; }

        public DBHelper()
        {
            this.ConnString = Config.ConectionString;
        }

        public DBHelper(string connect)
        {
            this.ConnString = connect;
        }

        /// <summary>
        /// 得到一个连接
        /// </summary>
        public MySqlConnection GetConn()
        {
            MySqlConnection conn = new MySqlConnection(this.ConnString);
            conn.Open();
            return conn;
        }

        /// <summary>
        /// 获取一个DataReader
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public MySqlDataReader GetDataReader(string sql)
        {
            using (MySqlCommand cmd = new MySqlCommand(sql, GetConn()))
            {
                return cmd.ExecuteReader(CommandBehavior.CloseConnection);
            }
        }
        /// <summary>
        /// 获取一个DataReader,带参数
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public MySqlDataReader GetDataReader(string sql, MySqlParameter[] param)
        {
            using (MySqlCommand cmd = new MySqlCommand(sql, GetConn()))
            {
                if (param != null && param.Length > 0)
                    cmd.Parameters.AddRange(param);
                MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                cmd.Parameters.Clear();
                return dr;
            }
        }
        /// <summary>
        /// 获取一个DataTable
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlDataAdapter dap = new MySqlDataAdapter(sql, conn))
                {
                    DataTable dt = new DataTable();
                    dap.Fill(dt);
                    dap.Dispose();
                    conn.Close();
                    return dt;
                }
            }
        }
        /// <summary>
        /// 获取一个DataTable,带参数
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    if (param != null && param.Length > 0)
                        cmd.Parameters.AddRange(param);
                    using (MySqlDataAdapter Dap = new MySqlDataAdapter(cmd))
                    {
                        DataTable dt = new DataTable();
                        Dap.Fill(dt);
                        cmd.Parameters.Clear();
                        Dap.Dispose();
                        cmd.Dispose();
                        conn.Close();
                        return dt;
                    }
                }
            }
        }
        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int Execute(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    int cnt = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    conn.Close();
                    return cnt;
                }
            }
        }

        /// <summary>
        /// 执行SQL-事务
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int Execute(string sql, MySqlTransaction trans)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Transaction = trans;
                    int cnt = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    conn.Close();
                    return cnt;
                }
            }
        }
        /// <summary>
        /// 执行SQL(事务)
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public int Execute(Dictionary<string, MySqlParameter[]> sqlList)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                int i = 0;
                MySqlTransaction trans = conn.BeginTransaction();
                try
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        foreach (var sql in sqlList)
                        {
                            cmd.Connection = conn;
                            cmd.CommandText = sql.Key;
                            if (sql.Value != null && sql.Value.Length > 0)
                                cmd.Parameters.AddRange(sql.Value.ToArray());
                            i += cmd.ExecuteNonQuery();
                            cmd.Parameters.Clear();
                            cmd.Dispose();
                        }
                    }
                    trans.Commit();
                    return i;
                }
                catch (MySqlException err)
                {
                    trans.Rollback();
                    throw new Exception(err.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }


        /// <summary>
        /// 执行Sql（事务）
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <param name="tran"></param>
        /// <returns></returns>

        public int Execute(string sql, MySqlParameter[] param, MySqlTransaction tran)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();

                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    if (param != null && param.Length > 0)
                        cmd.Parameters.AddRange(param);
                    cmd.Transaction = tran;
                    int cnt = cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    conn.Close();
                    return cnt;
                }
            }
        }


        /// <summary>
        /// 执行SQL(事务)
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string ExecuteScalar(Dictionary<string, MySqlParameter[]> sqlList)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                object value = null;
                MySqlTransaction trans = conn.BeginTransaction();
                try
                {
                    using (MySqlCommand cmd = new MySqlCommand())
                    {
                        foreach (var sql in sqlList)
                        {
                            cmd.Connection = conn;
                            cmd.CommandText = sql.Key;
                            if (sql.Value != null && sql.Value.Length > 0)
                                cmd.Parameters.AddRange(sql.Value.ToArray());
                            value = cmd.ExecuteScalar();
                            cmd.Parameters.Clear();
                            cmd.Dispose();
                        }
                    }
                    trans.Commit();
                    return value != null ? value.ToString() : string.Empty;
                }
                catch (MySqlException err)
                {
                    trans.Rollback();
                    throw new Exception(err.Message);
                }
                finally
                {
                    conn.Close();
                }
            }
        }
        /// <summary>
        /// 执行带参数的SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int Execute(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(param);
                    int r = -1;
                    r = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return r;
                }
            }
        }

        /// <summary>
        /// 执行带参数的SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string ExecuteScalar(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(param);
                    string r = string.Empty;
                    object obj = cmd.ExecuteScalar();
                    r = obj != null ? obj.ToString() : string.Empty;
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return r;
                }
            }
        }


        /// <summary>
        /// 执行带参数的SQL-事务
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string ExecuteScalar(string sql, MySqlParameter[] param, MySqlTransaction trans, MySqlConnection conns)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(param);
                    string r = string.Empty;
                    cmd.Transaction = trans;
                    object obj = cmd.ExecuteScalar();
                    r = obj != null ? obj.ToString() : string.Empty;
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return r;
                }
            }
        }


        /// <summary>
        /// 执行带参数的SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public int Execute(string sql, MySqlParameter[] param, out int identity)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    if (param != null && param.Length > 0)
                        cmd.Parameters.AddRange(param);
                    int i = cmd.ExecuteNonQuery();
                    MySqlCommand cmd1 = new MySqlCommand("SELECT LAST_INSERT_ID()", conn);
                    object MaxIDObject = cmd1.ExecuteScalar();
                    int MaxID;
                    identity = MaxIDObject != null && int.TryParse(MaxIDObject.ToString(), out MaxID) ? MaxID : -1;
                    cmd1.Dispose();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return i;
                }
            }
        }
        /// <summary>
        /// 得到一个字段的值
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string GetFieldValue(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return obj != null ? obj.ToString() : string.Empty;
                }
            }
        }
        /// <summary>
        /// 得到一个字段的值,带参数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public string GetFieldValue(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    if (param != null && param.Length > 0)
                        cmd.Parameters.AddRange(param);
                    object obj = cmd.ExecuteScalar();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return obj != null ? obj.ToString() : string.Empty;
                }
            }
        }
        /// <summary>
        /// 得到一个数据集,带参数
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public DataSet GetFieldDataSet(string sql, string CusNo)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    MySqlParameter param = new MySqlParameter("@CusNo", MySqlDbType.VarChar, 100);
                    param.Value = CusNo;
                    cmd.Parameters.Add(param);
                    MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    conn.Close();
                    return ds;
                }
            }
        }

        public DataSet GetFillingdDataSet(string sql)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {
                    MySqlDataAdapter sda = new MySqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    sda.Fill(ds);
                    cmd.Dispose();
                    conn.Close();
                    return ds;
                }
            }
        }
        ///// <summary>
        ///// 释放数据库连接
        ///// </summary>
        //public void Dispose()
        //{
        //    if (new MySqlConnection(this.connString) is MySqlConnection)
        //    {
        //        if (new MySqlConnection(this.connString) != null && new MySqlConnection(this.connString).State != ConnectionState.Closed)
        //        {
        //            try
        //            {
        //                new MySqlConnection(this.connString).Close();
        //            }
        //            catch (MySqlException err)
        //            { }
        //        }
        //        new MySqlConnection(this.connString).Dispose();
        //    }
        //}

        public int ExecuteNon(string sql, MySqlParameter[] param, MySqlTransaction tran, MySqlConnection conn)
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = conn;
                cmd.Transaction = tran;
                cmd.CommandText = sql;
                cmd.Parameters.AddRange(param);
                int r = -1;
                r = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                return r;
            }
        }

        public int ExecuteNon(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {

                    cmd.Parameters.AddRange(param);
                    int r = -1;
                    r = cmd.ExecuteNonQuery();
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    return r;
                }
            }

        }

        public int ExecuteNon1(string sql, MySqlParameter[] param)
        {
            using (MySqlConnection conn = new MySqlConnection(this.ConnString))
            {
                conn.Open();
                using (MySqlCommand cmd = new MySqlCommand(sql, conn))
                {

                    cmd.Parameters.AddRange(param);
                    int r = -1;
                    r = Convert.ToInt32(cmd.ExecuteScalar());
                    cmd.Parameters.Clear();
                    cmd.Dispose();
                    return r;
                }
            }

        }

        /// <summary>
        /// 执行sql-事务
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="tran"></param>
        /// <param name="conn"></param>
        /// <returns></returns>
        public int ExecuteNon(string sql, MySqlTransaction tran, MySqlConnection conn)
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = conn;
                cmd.Transaction = tran;
                cmd.CommandText = sql;
                int r = -1;
                r = cmd.ExecuteNonQuery();
                cmd.Parameters.Clear();
                cmd.Dispose();
                return r;
            }
        }
        /// <summary>
        /// 执行带参数的SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="param"></param>
        /// <returns></returns>
        public string ExecuteScalar(string sql, MySqlTransaction tran, MySqlConnection conn)
        {
            using (MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = conn;
                cmd.Transaction = tran;
                cmd.CommandText = sql;
                string r = string.Empty;
                object obj = cmd.ExecuteScalar();
                r = obj != null ? obj.ToString() : string.Empty;
                cmd.Parameters.Clear();
                cmd.Dispose();
                conn.Close();
                return r;
            }
        }
    }
}
